/****************************************************
文件：GroupModel.cs
作者：UnitySir
邮箱：zouajck@foxmail.com
日期：2021/07/30 09:55:47
功能：Nothing
*****************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;

public class GroupModel : MonoBehaviour
{
    private void Start()
    {
        DMComposite root = new DMComposite("Root");
        DMLeaf leaf1 = new DMLeaf("GameObject(1)");
        DMLeaf leaf2 = new DMLeaf("GameObject(2)");
        DMComposite gameobject3 = new DMComposite("GameObject(3)");

        root.AddChild(leaf1);
        root.AddChild(leaf2);
        root.AddChild(gameobject3);

        DMComposite gameobject4 = new DMComposite("GameObject(4)");

        gameobject3.AddChild(gameobject4);

        DMLeaf leaf3 = new DMLeaf("GameObject(5)");
        DMLeaf leaf4 = new DMLeaf("GameObject(6)");

        gameobject4.AddChild(leaf3);
        gameobject4.AddChild(leaf4);


        ReadComposite(root);
    }

    private void ReadComposite(DMComponent component)
    {
        Debug.Log($"对象名称 = {component.MName}");
        if (component is DMLeaf) return;
        var children = component.Children;
        foreach (var child in children)
        {
            ReadComposite(child);
        }
    }
}

public abstract class DMComponent
{
    protected string mName;

    public string MName => mName;

    protected List<DMComponent> mChildren;
    public List<DMComponent> Children => mChildren;

    public DMComponent(string mName)
    {
        mChildren = new List<DMComponent>();
        this.mName = mName;
    }

    public abstract void AddChild(DMComponent component);
    public abstract void RemoveChild(DMComponent component);
    public abstract DMComponent GetChild(int index);
}

public class DMLeaf : DMComponent
{
    public DMLeaf(string mName) : base(mName)
    {
    }

    public override void AddChild(DMComponent component)
    {
        throw new Exception("无法操作Leaf");
    }

    public override void RemoveChild(DMComponent component)
    {
        throw new Exception("无法操作Leaf");
    }

    public override DMComponent GetChild(int index)
    {
        throw new Exception("无法操作Leaf");
    }
}

public class DMComposite : DMComponent
{
    public DMComposite(string mName) : base(mName)
    {
    }

    public override void AddChild(DMComponent component)
    {
        mChildren.Add(component);
    }

    public override void RemoveChild(DMComponent component)
    {
        mChildren.Remove(component);
    }

    public override DMComponent GetChild(int index)
    {
        return mChildren[index];
    }
}